package cn.edu.fzu.delivery.helper;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ExecutorService;

@Component("emailHelper")
public class EmailHelper {

    private static final Logger log    = LoggerFactory.getLogger(EmailHelper.class);

    private static final String FZU    = "福州大学";

    private static final String SYSTEM = "--快递管理系统";

    private static final String UTF8   = "UTF-8";

    @Resource
    private JavaMailSenderImpl  mailSender;

    @Resource
    private ExecutorService     threadPool;

    /** 单发邮件 **/
    public boolean sendMail(String email, String title, String content) {
        if (StringUtils.isBlank(mailSender.getUsername())) {
            throw new RuntimeException("系统邮箱未配置");
        }
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, UTF8);
            messageHelper.setFrom(mailSender.getUsername(), FZU);
            messageHelper.setSubject(title + SYSTEM);
            messageHelper.setTo(email);
            messageHelper.setText(content, true);// html: true
            mailSender.send(mimeMessage);
        } catch (Exception e) {
            log.error("send email fail | email:{},title:{}", email, title, e);
            return false;
        }
        return true;
    }


    /** 群发邮件 **/
    public boolean sendGroupEmail(List<String> emails, String title, String content) {
        if (StringUtils.isBlank(mailSender.getUsername())) {
            throw new RuntimeException("系统邮箱未配置");
        }
        try {
            for (String email : emails) {
                MimeMessage mimeMessage = mailSender.createMimeMessage();
                MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, UTF8);
                messageHelper.setFrom(mailSender.getUsername(), FZU);
                messageHelper.setSubject(title + SYSTEM);
                messageHelper.setText(content, true);// html: true

                messageHelper.setTo(email);
                threadPool.submit(new Runnable() {
                    @Override
                    public void run() {
                        mailSender.send(mimeMessage);
                    }
                });
            }
        } catch (Exception e) {
            log.error("send group email fail | title:{}", title, e);
            return false;
        }
        return true;
    }

}
